package com.buding.fx.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author mingdongwei-jwk
 * @date 2022/12/08 14:46
 * @class com.buding.fx.netty
 * @Description
 */
public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("decoder",new StringDecoder());
                        pipeline.addLast("encoder",new StringEncoder());
                        //加入自己的业务处理handler
                        pipeline.addLast(new ChatClientHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9000).sync();
        //得到channel
        Channel channel = channelFuture.channel();
        System.out.println("==========="+ channel.localAddress() + "===============");
        //客户端需要输入信息，创建一个扫描器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            //通过channel发送到服务器端
            channel.writeAndFlush(msg);
        }

    }
}
